package com.hsf.cloudweb.utils;

import com.hsf.cloudweb.config.HttpsApiConfig;
import com.hsf.cloudweb.factory.HttpsClientRequestFactory;
import com.hsf.cloudweb.model.MsmRespInfo;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;

public class RestTemplateUtil {

    private static RestTemplate restTemplate;
    static{
        ClientHttpRequestFactory clientHttpRequestFactory = new HttpsClientRequestFactory();
        ((HttpsClientRequestFactory) clientHttpRequestFactory).setConnectTimeout(30000);
        ((HttpsClientRequestFactory) clientHttpRequestFactory).setReadTimeout(180000);
        restTemplate = new RestTemplate(clientHttpRequestFactory);
    }


    public static String createCommonParam(String sid,String token) {
        // 时间戳
        long timestamp = System.currentTimeMillis();
        // 签名
        String sig = DigestUtils.md5Hex(sid + token + timestamp);

        StringBuilder builder = new StringBuilder("&timestamp=");

        builder.append(timestamp).append("&sig=").append(sig).append("&respDataType=").append(HttpsApiConfig.RESP_DATA_TYPE);

        return builder.toString();
    }

     public static MsmRespInfo post(String url, String body) throws Exception{
         //设置请求头信息
         HttpHeaders httpHeaders = new HttpHeaders();
         //设置请求头Content-Type值为application/x-www-form-urlencoded
         httpHeaders.add("Content-Type","application/x-www-form-urlencoded");
         HttpEntity<String> requestEntity = new HttpEntity<>(body,httpHeaders);
         ResponseEntity<MsmRespInfo> responseEntity = restTemplate.exchange(url,HttpMethod.POST,requestEntity, MsmRespInfo.class);
         return responseEntity.getBody();
     }






}
